package main

import (
	"common/comRsa"
	"common/gateway"
	"common/response"
	"context"
	"flag"
	"fmt"
	"gateway/internal/middleware"
	"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
	"google.golang.org/grpc"
	"net/http"

	"gateway/internal/config"
	"gateway/internal/handler"
	"gateway/internal/svc"

	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/rest"
)

var configFile = flag.String("f", "etc/gateway.yaml", "the config file")

func main() {
	flag.Parse()

	var c config.Config
	conf.MustLoad(*configFile, &c)
	comRsa.SetUp("etc/PRIVATEKEY.pem", "etc/PUBLICKEY.pem")
	RpcServers := gateway.HeperFace{
		GrpcEndpoint:  c.ChatRpcClientConf.Target,
		RegisterFuncs: []func(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error){},
	}
	Gh, _ := gateway.GrpcHandler(
		context.Background(),
		[]func(http.HandlerFunc) http.HandlerFunc{middleware.NewUserInfoMiddleware(c).Handle},
		[]gateway.HeperFace{RpcServers},
	)
	server := rest.MustNewServer(c.RestConf, rest.WithNotFoundHandler(Gh), rest.WithUnauthorizedCallback(response.JwtUnauthorizedResult))
	defer server.Stop()

	ctx := svc.NewServiceContext(c)
	handler.RegisterHandlers(server, ctx)

	fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
	server.Start()
}
